<template>
  <v-app>
    <v-main>
      <v-container>
        <v-row class="text-center">
    <v-dialog
      v-model="dialog"
      persistent
      max-width="600px"
    >
      <v-card>
        <v-form
    ref="form"
    v-model="valid"
    lazy-validation
  >
        <v-card-title>
          <span class="headline">录入信息</span>
        </v-card-title>
        <v-card-text>
          <v-container>
            
            <v-row>
              <v-col
                cols="12"
                sm="6"
              >
                <v-select
                  v-model="select"
                  :items="items"
                  item-text="text"
                  item-value="value"
                  label="学校"
                  :rules="[v => !!v || '您还没选择学校']"
                  required
                ></v-select>
              </v-col>
              <v-col
                cols="12"
                sm="6"
                md="6"
              >
                <v-text-field
                  v-model="card"
                  label="卡号"
                  disabled
                ></v-text-field>
              </v-col>
              <v-col
                cols="12"
                sm="6"
                md="6"
              >
                <v-text-field
                  v-model="name"
                  label="学生姓名"
                  :rules="[v => !!v || '您还没填入学生姓名']"
                ></v-text-field>
              </v-col>
              <v-col
                cols="12"
                sm="6"
                md="6"
              >
                <v-text-field
                v-model="phone"
                  label="家长手机号"
                  :rules="phoneRules"
                  :counter="11"
                  required
                ></v-text-field>
              </v-col>
              
            </v-row>
            
          </v-container>
          <!-- <small>*indicates required field</small> -->
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="red darken-1"
            text
            @click="dialog = false"
          >
            关闭
          </v-btn>
          <v-btn
            color="blue darken-1"
            text
            :disabled="!valid"
            class="mr-4"
            @click="save"
          >
            保存
          </v-btn>
        </v-card-actions>
        </v-form>
      </v-card>
    </v-dialog>

          <v-col class="my-4">
            <h1 class="display-2 font-weight-bold mb-3">
              {{ record }}
            </h1>
          </v-col>
          <v-col cols="12">
            <v-card elevation="16" max-width="400" class="mx-auto">
              <v-virtual-scroll :items="records" height="1000" item-height="64">
                <template v-slot:default="{ item }">
                  <v-list-item :key="item">
                    <v-list-item-content @click="showDialog(item)">
                      <v-list-item-title>
                        <strong>{{ item }}</strong>
                      </v-list-item-title>
                    </v-list-item-content>
                  </v-list-item>
                  <v-divider></v-divider>
                </template>
              </v-virtual-scroll>
            </v-card>
          </v-col>
        </v-row>
      </v-container>
      <v-snackbar
      v-model="snackbar"
    >
      {{ text }}

      <template v-slot:action="{ attrs }">
        <v-btn
          color="primary"
          text
          v-bind="attrs"
          @click="snackbar = false"
        >
          关闭
        </v-btn>
      </template>
    </v-snackbar>

    </v-main>
  </v-app>
</template>

<script>
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
  env: "school-10be94",
});

const auth = app.auth();

export default {
  name: "App",

  data: () => ({
    record: "暂无数据",
    records: [],
    text:'',
    snackbar:false,
    dialog: false,
    valid: false,
    select:'',
    items: [
          { text: '新昌城南幼儿园', value: 'xccn' },
          { text: '章镇王充小学', value: 'zzwc' },
          { text: '上浦联江小学', value: 'splj' },
          { text: '上虞华维初中', value: 'syhw' }
        ],
    card:'',
    name:'',
    phone:'',
    phoneRules: [
        v => !!v || '您还没有输入手机号',
        v => (v && v.length == 11) || '手机号格式有误',
      ],
  }),

  async created() {
    let loginState = await this.login();
    if (loginState) {
      // this.getRank()
      this.watchData();
    } else {
      alert("异常错误，请联系管理员！");
    }
  },
  methods: {
    async login() {
      const loginState = await auth.getLoginState();
      // console.log('login', loginState)
      // 1. 建议登录前检查当前是否已经登录
      if (!loginState) {
        // 2. 请求开发者自有服务接口获取ticket
        const ticket = (
          await this.axios.post(
            "https://school-10be94-1258099036.ap-shanghai.app.tcloudbase.com/newcard",
            { method: "login" }
          )
        ).data;
        // 3. 登录 CloudBase
        const loginBack = await auth.customAuthProvider().signIn(ticket);
        // 4. 返回登录状态
        if (!loginBack) {
          return 0;
        } else {
          return 1;
        }
      } else {
        return 1;
      }
    },
    async watchData() {
      await app
        .database()
        .collection("newcard")
        .watch({
          onChange: (snapshot) => {
            // console.log('收到snapshot**********', snapshot)
            this.record = snapshot.docChanges[0].doc.data;
            this.records.unshift(snapshot.docChanges[0].doc.data);
          },
          onError: (error) => {
            console.log("收到error**********", error);
          },
        });
    },
    showDialog(item) {
      // this.dialog = true;
      // this.card = '1111111'
      if(item.split("：")[0]=="New Card"){
        this.card = item.split("：")[1];
        this.dialog = true;
      }
      
    },
    save(){
      if(this.phone&&this.name&&this.select){
        this.addCard();
      }else{
        this.$refs.form.validate()
      }
    },
    async addCard(){
      var data = {phone:parseInt(this.phone),name:this.name,school:this.select,card:parseInt(this.card),num:0};
      await app
        .database()
        .collection("school").add(data).then(res=>{console.info(res);this.text ="添加成功";this.snackbar = true;}).catch(console.error)
      this.phone = '';
      this.card = '';
      this.name = '';
      this.dialog = false;
    }
  },
};
</script>
